<?php

session_start();
require_once '../data/connect.class.php';
require_once('../data/smtp.class.php');

class TaskOpt {
	
	var $connection;
	function TaskOpt($conn) {
		$this->connection = $conn;
	}
	function createTemplate($templateName,$template_path,$creator_id,$creator_name,$create_time) {

		$sql = "insert into admin_mail_template(name,template_path,creator_id,creator_name,create_time) ";
		$sql .= "values('";
		$sql .= $templateName;
		$sql .= "','";
		$sql .= $template_path;
		$sql .= "',";
		$sql .= $creator_id;
		$sql .= ",'";
		$sql .= $creator_name;
		$sql .= "',";
		$sql .= $create_time;
		$sql .= ")";
		echo $sql;
		$this->connection->execute($sql);
	}
	
	function delTemplate($id) {
		$param = array('id'=>$id);
		$this->connection->delSql('admin_mail_template',$param);
	}
	
	function addTask($task_name,$template_id,$addrs,$reply_name,$reply_addr,$smtp_id,$userId,$username) {

		$templateSql = "select name from admin_mail_template where id=".$template_id;
		$resultSet = $this->connection->execute($templateSql);
		$templateName = $resultSet[0]['name'];
		$date = time();
		
		$smtpSql = "select name from admin_smtp_server where id=".$smtp_id;
		$smtpSet = $this->connection->execute($smtpSql);
		$smtp_name = $smtpSet[0]['name'];
		$status = 0;
		$array = array("name"=>$task_name,
		               "creator_id"=>$userId,
		               "creator_name"=>$username,
					   "create_time"=>$date,
				       "template_id"=>$template_id,
				       "template_name"=>$templateName,
		               "reply_addr"=>$reply_addr,
					   "reply_name"=>$reply_name,
				       "smtp_server_id"=>$smtp_id,
					   "smtp_server_name"=>$smtp_name,
				       "status"=>$status
		);
		$this->connection->insertSql("admin_task",$array);
		
		$taskId = $this->connection->getInsertID();
		foreach($addrs as $addr) {
			if (strlen(trim($addr)) > 0) {
				$taskArray = array("task_id"=>$taskId,
		               "addr_id"=>$addr);
				$this->connection->insertSql("admin_task_addr",$taskArray);
			}
		}
		
	}
	
	function initMailParams($id) {
		
		$array = array();
		
		$sql = "select * from admin_smtp_server as ass, admin_task as at where at.smtp_server_id = ass.id and at.id=".$id." and ass.status<>0;";
		$resultset = $this->connection->Query($sql);
		
		$res = $resultset[0];
		$array['AuthUser'] = $res['user_name'];
		$array['AuthPass'] = $res['password'];
		$array['Host'] = $res['host'];
		$array['Port'] = $res['port'];
		$array['From'] = $res['from_addr'];
		
		$array['reply_addr'] = $res['reply_addr'];
		$array['reply_name'] = $res['reply_name'];
		
		$sql = "select * from admin_mail_template as amt, admin_task as at where at.template_id = amt.id and at.id=".$id;
		$resultset = $this->connection->Query($sql);
	    $res = $resultset[0];
		$array['template_path'] = $res['template_path'];
		return $array;
	}
	
	function updateStatus($id,$status) {
		$array = array('status'=>$status);
		$this->connection->updateSql("admin_task",$array,"id=".$id);
	}
}

$connect = new Connect("localhost","root","","email");
$taskOpt = new TaskOpt($connect);
$opt=$_POST['opt'];

if (isset($opt)) {
	if ($opt=='createTemplate') {
		$templateName = $_POST['templateName'];
		
		if(mb_detect_encoding($templateName)!='UTF-8'){
	        $templateName = utf8_encode($templateName);
	    }
	    		
		$templateContent = $_POST['templateContent'];
		$decodedContent = urldecode($templateContent);
		$date = time();
		$encodeName = iconv("UTF-8","GB2312//IGNORE",$templateName);
		$filePath = "/resources/templates/".$encodeName.$date.".html";
		$dbPath = "/resources/templates/".$templateName.$date.".html";
		$file = fopen("..".$filePath , "x+");
		$content = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head><body>".$decodedContent."</body></html>";
		fwrite($file,$content);
		fclose($file);
		
		$userId = $_SESSION['userId'];
		$userName = $_SESSION['suser'];
		$taskOpt->createTemplate($templateName,$dbPath,$userId,$userName,$date);
	}
	if ($opt=='delTemplate') {
		$id = $_POST['id'];
		$taskOpt->delTemplate($id);
	}
	if ($opt=='addTask') {
		$task_name = $_POST['task_name'];
		$template_id = $_POST['template_id'];
		$addrs = trim($_POST['addrs']);
		$reply_name = $_POST['reply_name'];
		$reply_addr = $_POST['reply_addr'];
//		$smtp_id = $_POST['smtp_id'];
		$userId = $_SESSION['userId'];
		$username = $_SESSION['suser'];
		$domains = stripslashes(trim($_POST['domains']));
		$classes = trim($_POST['classes']);
		
		$allAddrs = array();
		$sql = "select distinct id from admin_mail_addr where ";
		$isFirst = true;
		if (isset($addrs) && strlen($addrs) > 0) {
			$sql .= "id in (".$addrs.") ";
			$isFirst = false;
		}
		if (isset($domains) && strlen($domains) > 0) {
	    	if ($isFirst) {
	    		$sql .= "domain in (".$domains.") ";
	    		$isFirst = false;
	    	} else {
	    		$sql .= " or domain in (".$domains.") ";
	    	}
		}
	    if (isset($classes) && strlen($classes) > 0) {
	        if ($isFirst) {
	    		$sql .= "class_id in (".$classes.") ";
	    		$isFirst = false;
	    	} else {
	    		$sql .= " or class_id in (".$classes.") ";
	    	}
		}
		
		if ($isFirst) {
			return;
		}
//		echo $sql;
		$resultSet = $connect->execute($sql);
		foreach ($resultSet as $res) {
			$allAddrs[] = $res['id'];
		}
		
//		print_r($allAddrs);
		$taskOpt->addTask($task_name,$template_id,$allAddrs,$reply_name,$reply_addr,$smtp_id,$userId,$username);
	}
	if ($opt=='sendTask') {
		
		$id = $_POST['id'];

		$mailParams = $taskOpt->initMailParams($id);
		
        $mail=new smtp_class;
        
		$mail->Timeout        = 10;  // SMTP connection timeout. Default: 10; 
		$mail->Timezone        = "+0800";  // Time Zone. Default: "+0000"; 
		$mail->Priority        = 3;  // Email priority Default: 3 (1=High,3=Medium or 5=Low); 
		$mail->CharSet        = "UTF-8";  // Character set. 
		$mail->WordWrap        = 0;  // characters per line. 0 for umlimit characterc per line 
		$mail->IsHTML        = true;  // HTML email. Default: false (true or false); 
		$mail->MailerDebug    = true;  // Display SMTP error. Default: false (true or false); 
		$mail->AuthLogin    = true;  // using SMTP authorization. Default: false (true or false); 
		
		$mail->AuthUser        = $mailParams['AuthUser'];  // SMTP username 
		$mail->AuthPass        = $mailParams['AuthPass'];  // SMTP password 
		$mail->Host            = $mailParams['Host'];  // SMTP server. like smtp.21cn.com
		$mail->Port            = $mailParams['Port'];  // SMTP port. Default: 25; 
		# email address and content start here 
		$mail->From($mailParams['From'],"dan"); 
		$mail->AddReplyTo($mailParams['reply_addr'],$mailParams['reply_name']); 
		
		$mail->Subject="hihi"; 
		$contentPath = "..".$mailParams['template_path'];
		
		$file = fopen($contentPath,'r');
		$contents = fread($file, filesize ($contentPath));
		fclose($file);
		$mail->Body = $contents;
		
		$taskOpt->updateStatus($id,1);
		$sql = "select * from admin_task_addr as ata, admin_mail_addr as ama where ata.task_id=".$id." and ata.addr_id=ama.id and ama.subcripted=1";
		$resultset = $connect->Query($sql);
		
		foreach ($resultset as $res) {
			$mail->AddTo($res['mail_addr'],$res['name']); 
			
		}
		
        $mail->Send();
        $taskOpt->updateStatus($id,2);
	}
}

?>